package week_02;

public class IsValidBST_98 {
    public boolean isValidBST(TreeNode root) {
        return check(root).isBST;
    }

    public Info check(TreeNode node) {
        // 空终止
        if (node == null) return new Info();
        // 需要收集：最大值，最小值，isBST
        // 收集左树信息
        Info leftInfo = check(node.left);
        //收集右树信息
        Info rightInfo = check(node.right);
        // 处理当前节点的信息
        boolean isBST = leftInfo.isBST && rightInfo.isBST
                && (node.val > leftInfo.max) && (node.val < rightInfo.min);

        long max = Math.max(Math.max(leftInfo.max, rightInfo.max), node.val);
        long min = Math.min(Math.min(leftInfo.min, rightInfo.min), node.val);
        // 返回结果
        Info info = new Info(max, min, isBST);
        return info;
    }

    public class Info {
        private long max;
        private long min;
        private boolean isBST;

        public Info() {
            this.max = Long.MIN_VALUE;
            this.min = Long.MAX_VALUE;
            this.isBST = true;
        }

        public Info(long max, long min, boolean isBST) {
            this.max = max;
            this.min = min;
            this.isBST = isBST;
        }
    }
}
